import axios from 'axios'
import store from '@/store/index.js'
import router from '@/router'

const request = axios.create({
  baseURL: 'http://ttapi.research.itcast.cn/' // 基础路径
  // baseURL: 'http://toutiao-app.itheima.net/'
})

/* axios的请求拦截器 */
request.interceptors.request.use(
  function(config) {
    // console.log('config:', config)
    const { user } = store.state
    if (user && user.token) {
      config.headers.Authorization = `Bearer ${user.token}`
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)
/* axios的响应拦截器 */
request.interceptors.response.use(
  function(response) {
    return response
  },
  function(error) {
    console.log('login2')
    console.log('error:', error)
    if (error.response.status === 401) {
      console.log('login')
      router.replace({
        path: '/login' // 到登录页重新获取token
      })
    }
    return Promise.reject(error)
  }
)

export default request
